<template>
  <div class="app-container">
    <!-- 列表页面 -->
    <div v-if="!showEdit">
      <!-- 搜索区域 -->
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        class="search-form"
        label-width="100px"
      >
        <el-form-item label="工艺名称">
          <el-input
            v-model="queryParams.templateName"
            placeholder="请输入工艺名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input
            v-model="queryParams.productNames"
            placeholder="请输入产品名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 操作工具栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增
          </el-button>
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="templateList"
        height="400"
        :row-style="{ height: '30px' }"
        border
        :cell-style="{ padding: '0px' }"
      >
        <el-table-column
          label="工艺名称"
          align="center"
          prop="templateName"
          :show-overflow-tooltip="true"
          width="280"
        />
        <el-table-column
          label="产品名称"
          align="center"
          prop="productNames"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="阶段名称"
          align="center"
          prop="stageNames"
          :show-overflow-tooltip="true"
          width="950"
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="creationTime"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="80"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              title="修改"
            ></el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              title="删除"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 设计页面 -->
    <div v-else class="design-container">
      <!-- 基本信息 -->
      <div class="design-header">
        <el-form
          :model="form"
          label-width="70px"
          :rules="formRules"
          ref="formRef"
        >
          <!-- 第一行 -->
          <el-row :gutter="24">
            <el-col :span="5">
              <el-form-item label="工艺名称" prop="templateName">
                <el-input
                  v-model="form.templateName"
                  placeholder="请输入工艺名称"
                  :title="form.templateName"
                  style="text-align: left"
                  @blur="validateTemplateName"
                  :loading="validating"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="产品名称" prop="productName">
                <div class="product-select">
                  <el-input
                    v-model="form.productName"
                    placeholder="请选择产品"
                    style="width: 600px"
                    :title="form.productName"
                    readonly
                  />
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleSelectProduct"
                    >选择
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="流程阶段">
                <el-input
                  v-model="flowStagesText"
                  placeholder="请拖拽阶段到流程图"
                  readonly
                  :title="flowStagesText"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="design-content">
        <!-- 左侧阶段列表 -->
        <div class="stage-list">
          <div class="stages-container">
            <div
              v-for="(stage, index) in stageList"
              :key="stage.id"
              class="stage-item"
              draggable="true"
              @dragstart="handleDragStart($event, stage)"
            >
              <el-input
                v-model="stage.stageName"
                class="stage-input"
                maxlength="50"
                :title="stage.stageName"
                placeholder="请输入阶段名称"
                @blur="handleStageNameChange(stage)"
              />
              <i
                class="el-icon-close delete-icon"
                @click="handleStageDelete(index)"
              ></i>
            </div>
            <p v-if="stageList.length === 0" class="no-data">暂无数据</p>
          </div>

          <el-button
            type="primary"
            class="add-stage-btn"
            @click="handleAddStage"
            >新增阶段
          </el-button>
        </div>

        <!-- 右侧流程图 -->
        <div
          class="flow-chart"
          ref="flowContainer"
          @dragover.prevent
          @drop="handleDrop"
        >
          <div
            v-for="stage in flowStages"
            :key="stage.id"
            :id="stage.id"
            class="flow-node"
            :class="{ active: selectedStage && selectedStage.id === stage.id }"
            :style="stage.style"
            @click="handleStageClick(stage)"
          >
            <span class="node-text">{{ stage.stageName }}</span>
            <i
              class="el-icon-close delete-icon"
              @click.stop="deleteFlowStage(stage)"
            ></i>
          </div>
        </div>
      </div>

      <!-- 成果管理列表 -->
      <div v-if="selectedStage" class="achievement-container">
        <div class="achievement-header">
          <div class="achievement-title">
            <h3>当前阶段：{{ selectedStage.stageName }}</h3>
          </div>
          <el-button
            type="primary"
            size="small"
            plain
            icon="el-icon-plus"
            @click="handleAddAchievement"
            >新增成果
          </el-button>
        </div>
        <el-table :data="achievementList" border class="achievement-table">
          <el-table-column label="成果名称" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.achievementName"
                placeholder="请输入成果名称"
                maxlength="90"
              />
            </template>
          </el-table-column>
          <el-table-column label="成果是否必要" width="120" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isRequired" placeholder="请选择">
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteAchievement(scope.$index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 底部按钮 -->
      <div class="design-footer">
        <el-button type="primary" @click="handleSubmit">保 存</el-button>
        <el-button @click="handleCancel">关 闭</el-button>
      </div>

      <!-- 产品选择弹窗 -->
      <el-dialog
        title="选择产品"
        :visible.sync="productDialogVisible"
        width="65%"
      >
        <el-form
          :model="queryProductParams"
          ref="queryProductForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="产品类别" prop="productType">
            <el-select
              v-model="queryProductParams.productType"
              placeholder="请选择产品类别"
              style="width: 150px"
              clearable
            >
              <el-option
                v-for="dict in dict.type.product_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-input
              v-model="queryProductParams.productName"
              placeholder="请输入产品名称"
              clearable
              style="width: 150px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="产品编号" prop="productNo">
            <el-input
              v-model="queryProductParams.productNo"
              placeholder="请输入产品编号"
              clearable
              style="width: 150px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQueryProduct"
              >搜索
            </el-button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQueryProduct"
              >重置
            </el-button>
            <el-button type="primary" size="mini" @click="confirmProductSelect"
              >确定
            </el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="productList"
          @selection-change="handleProductSelectionChange"
          ref="productTable"
          row-key="id"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="序号"
            type="index"
            :index="indexMethod"
            align="center"
          />
          <el-table-column label="产品名称" prop="productName" align="center" />
          <el-table-column label="产品编码" prop="productNo" align="center" />
          <el-table-column label="产品类别" align="center" prop="productType">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.product_type"
                :value="scope.row.productType"
              />
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="productTotal > 0"
          :total="productTotal"
          :page.sync="queryProductParams.pageNum"
          :limit.sync="queryProductParams.pageSize"
          @pagination="getProductList"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  listTemplate,
  getTemplate,
  addTemplate,
  updateTemplate,
  delTemplate,
  checkTemplateNameUnique,
} from "@/api/processmanagement/template";
import { listStage, addStage, delStage } from "@/api/stage/stage";
import { listQualification } from "@/api/qualificationInfo/qualification";
import { jsPlumb } from "jsplumb";
import { debounce } from "lodash";

export default {
  name: "ProcessTemplate",
  dicts: ["product_type"],
  data() {
    return {
      nodeSpacing: 200, // 统一的节点间距
      nodeBaseLeft: 50, // 统一的起始位置
      validating: false,
      debouncedValidate: null,
      opt: "add",
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: false,
      // 显示编辑视图
      showEdit: false,
      // 总条数
      total: 0,
      productTotal: 0,
      // 模板列表数据
      templateList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        templateName: undefined,
        productNames: undefined,
      },
      queryProductParams: {
        pageNum: 1,
        pageSize: 5,
        productType: null,
        productStatus: null,
        productNo: null,
        productName: null,
      },
      // 表单参数
      form: {
        id: undefined,
        templateName: undefined,
        productName: undefined,
        productId: undefined,
      },
      formRules: {
        templateName: [
          { required: true, message: "请输入工艺名称", trigger: "blur" },
          { min: 1, max: 90, message: "长度不能超过90字符", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "请选择产品", trigger: "change" },
          { min: 1, max: 900, message: "长度不能超过900字符", trigger: "blur" },
        ],
      },
      // 左侧阶段列表
      stageList: [],
      // 右侧流程图数据
      flowStages: [],
      // 已使用的阶段
      usedStages: new Set(),
      // 阶段ID计数器
      stageIdCounter: 1,
      // 连接记录
      connections: [],
      // 拖拽状态
      draggedStage: null,
      // jsPlumb实例
      jsPlumbInstance: null,
      // 当前选中的阶段
      selectedStage: null,
      // 当前阶段的成果列表
      achievementList: [],
      // 存储所有阶段的成果列表
      stageAchievements: {},
      // 产品选择弹窗
      productDialogVisible: false,
      // 产品列表
      productList: [],
      // 选中的产品
      selectedProducts: [],
    };
  },
  created() {
    this.getStageList().then(() => {
      this.getList();
      this.getProductList();
    });
    this.debouncedValidate = debounce(this.validateTemplateName, 300);
  },
  async mounted() {
    if (this.showEdit) {
      await this.$nextTick();
      await this.rebuildFlowChart();
    }
  },

  watch: {
    async showEdit(newVal) {
      if (newVal) {
        await this.getStageList();
        await this.$nextTick();
        await this.rebuildFlowChart();
      } else {
        if (this.jsPlumbInstance) {
          this.jsPlumbInstance.reset();
          this.jsPlumbInstance.destroy();
          this.jsPlumbInstance = null;
        }
      }
    },
  },
  computed: {
    flowStagesText() {
      return this.flowStages.map(stage => stage.stageName).join(",");
    },
  },
  beforeDestroy() {
    if (this.jsPlumbInstance) {
      this.jsPlumbInstance.reset();
      this.jsPlumbInstance = null;
    }
  },
  methods: {
    /** 查询模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    indexMethod(index) {
      return (
        (this.queryProductParams.pageNum - 1) *
          this.queryProductParams.pageSize +
        index +
        1
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleQueryProduct() {
      this.queryProductParams.pageNum = 1;
      this.getProductList();
    },

    resetQueryProduct() {
      this.queryProductParams.productStatus = null;
      this.resetProduct();
      this.handleQueryProduct();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.templateName = null;
      this.queryParams.productNames = null;
      this.handleQuery();
    },

    validateTemplateName() {
      const templateName = this.form.templateName;
      if (!templateName) {
        // 添加空值检查
        return;
      }
      this.validating = true;
      const id = this.form.id;
      // 修改调用方式，确保传递参数
      checkTemplateNameUnique(templateName, id)
        .then(response => {
          if (!response.data) {
            this.$message.error("模板名称已存在");
            this.form.templateName = "";
          }
        })
        .finally(() => {
          this.validating = false;
        });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.opt = "add";
      this.form.id = this.generateUUID();
      this.$nextTick(() => {
        this.showEdit = true; // 显示编辑视图
        this.initJsPlumb();
      });
    },

    resetProduct() {
      this.queryProductForm = {
        productType: null,
        productNo: null,
        productName: null,
      };
      this.resetForm("queryProductForm");
    },

    /** 编辑按钮操作 */
    handleEdit(row) {
      this.reset();
      this.opt = "edit";
      // 获取模板详情
      getTemplate(row.id)
        .then(async response => {
          const templateData = response.data;
          // 1. 填充基本表单数据
          this.form = {
            id: templateData.id,
            templateName: templateData.templateName,
            productName: templateData.productNames,
            productId: templateData.productIds,
          };
          // 2. 处理流程阶段数据
          if (templateData.stages && templateData.stages.length > 0) {
            this.flowStages = templateData.stages.map(stage => ({
              id: stage.id,
              templateId: stage.templateId,
              stageName: stage.stageName,
              originalId: stage.stageId,
              style: {
                position: "absolute",
                left: `${stage.positionX || 50}px`,
                top: `${stage.positionY || 200}px`,
                width: "120px",
                height: "40px",
              },
            }));
            // 3. 初始化阶段成果数据
            this.stageAchievements = {};
            templateData.stages.forEach(stage => {
              if (stage.achievements && stage.achievements.length > 0) {
                this.stageAchievements[stage.id] = stage.achievements;
              }
            });
            // 4. 标记已使用的阶段
            this.usedStages = new Set(
              this.flowStages.map(stage => stage.originalId)
            );
          }
          // 5. 获取所有阶段列表
          const stageRes = await listStage({ pageNum: 1, pageSize: 150 });
          if (stageRes.code === 200) {
            this.stageList = stageRes.rows || [];
          }

          // 6. 等待所有准备工作完成后再显示页面
          await new Promise(resolve => {
            setTimeout(async () => {
              try {
                // 初始化 jsPlumb
                if (this.jsPlumbInstance) {
                  this.jsPlumbInstance.reset();
                  this.jsPlumbInstance.destroy();
                }
                this.jsPlumbInstance = jsPlumb.getInstance({
                  Container: this.$refs.flowContainer,
                  Connector: [
                    "Flowchart",
                    {
                      stub: [30, 30],
                      gap: 10,
                      cornerRadius: 5,
                      alwaysRespectStubs: true,
                    },
                  ],
                  Endpoint: ["Dot", { radius: 4 }],
                  PaintStyle: { stroke: "#409EFF", strokeWidth: 2 },
                  EndpointStyle: { fill: "#409EFF" },
                  HoverPaintStyle: { stroke: "#409EFF", strokeWidth: 3 },
                  ConnectionsDetachable: false,
                  Anchors: ["Right", "Left"],
                });
                // 显示编辑视图
                this.showEdit = true;
                // 等待 DOM 更新
                await this.$nextTick();
                // 重新排列节点
                this.rearrangeFlowStages();
                // 再次等待 DOM 更新
                await this.$nextTick();
                // 创建连接
                this.flowStages.forEach((stage, index) => {
                  if (index > 0) {
                    const sourceId = this.flowStages[index - 1].id;
                    const targetId = stage.id;

                    this.jsPlumbInstance.connect({
                      source: sourceId,
                      target: targetId,
                      anchors: ["Right", "Left"],
                      endpoint: ["Dot", { radius: 4 }],
                      connector: [
                        "Flowchart",
                        {
                          stub: [30, 30],
                          gap: 10,
                          cornerRadius: 5,
                          alwaysRespectStubs: true,
                        },
                      ],
                      paintStyle: { stroke: "#409EFF", strokeWidth: 2 },
                      overlays: [
                        ["Arrow", { location: 1, width: 10, length: 10 }],
                      ],
                    });
                  }
                });

                resolve();
              } catch (error) {
                console.error("初始化流程图失败:", error);
                resolve();
              }
            }, 200); // 添加一个小延迟确保 DOM 完全准备好
          });
        })
        .catch(error => {
          console.error("获取模板详情失败:", error);
          this.$modal.msgError("获取模板详情失败");
        });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除该流程模板？")
        .then(() => {
          return delTemplate(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        templateName: undefined,
        productName: undefined,
        productId: undefined,
      };
      this.flowStages = [];
      this.connections = [];
      this.selectedStage = null;
      this.achievementList = [];
      this.stageAchievements = {};
      this.usedStages = new Set();
      this.selectedProducts = [];
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      // 获取所有阶段列表
      listStage().then(res => {
        this.stageList = res.rows || [];
        this.$nextTick(() => {
          this.initJsPlumb();
        });
      });
    },

    /** 初始化jsPlumb */
    initJsPlumb() {
      try {
        if (this.jsPlumbInstance) {
          this.jsPlumbInstance.reset();
        }
        // 确保容器元素存在
        if (!this.$refs.flowContainer) {
          console.warn("Flow container not found");
          return;
        }
        // 创建新实例
        this.jsPlumbInstance = jsPlumb.getInstance();
        // 设置容器
        this.jsPlumbInstance.setContainer(this.$refs.flowContainer);
        // 配置默认值
        this.jsPlumbInstance.importDefaults({
          Connector: ["Flowchart", { cornerRadius: 5 }],
          Endpoint: ["Dot", { radius: 4 }],
          PaintStyle: { stroke: "#409EFF", strokeWidth: 2 },
          EndpointStyle: { fill: "#409EFF" },
          HoverPaintStyle: { stroke: "#409EFF", strokeWidth: 3 },
          ConnectionsDetachable: false,
          Anchors: ["Right", "Left"],
        });

        // 重新渲染现有连接
        this.$nextTick(() => {
          this.flowStages.forEach((stage, index) => {
            if (index > 0) {
              const sourceElement = document.getElementById(
                this.flowStages[index - 1].id
              );
              const targetElement = document.getElementById(stage.id);

              if (sourceElement && targetElement) {
                this.jsPlumbInstance.connect({
                  source: sourceElement,
                  target: targetElement,
                  anchors: ["Right", "Left"],
                  endpoint: ["Dot", { radius: 4 }],
                  connector: ["Flowchart", { cornerRadius: 5 }],
                  paintStyle: { stroke: "#409EFF", strokeWidth: 2 },
                  overlays: [
                    [
                      "Arrow",
                      {
                        location: 1,
                        width: 10,
                        length: 10,
                      },
                    ],
                  ],
                });
              }
            }
          });
        });
      } catch (error) {
        console.error("Error initializing jsPlumb:", error);
      }
    },

    /** 阶段名称变更时保存 */
    handleStageNameChange(stage) {
      // 如果名称为空
      if (!stage.stageName || stage.stageName.trim() === "") {
        if (stage.isNew) {
          const index = this.stageList.findIndex(s => s.id === stage.id);
          if (index !== -1) {
            this.stageList.splice(index, 1);
          }
        }
        return;
      }

      // 如果是新阶段，则保存到数据库
      if (stage.isNew) {
        const params = {
          stageName: stage.stageName.trim(),
        };

        addStage(params)
          .then(response => {
            if (response.code === 200) {
              // 处理不同的返回数据结构
              const newStage = {
                id: response.data?.id || response.data, // 如果 response.data 是对象就取 id，否则直接使用
                stageName: stage.stageName.trim(),
                isNew: false,
              };
              // 找到临时阶段的索引
              const index = this.stageList.findIndex(s => s.id === stage.id);
              if (index !== -1) {
                // 使用 Vue.set 或 this.$set 来确保响应式更新
                this.$set(this.stageList, index, newStage);
              }
              this.$message.success("新增成功");
              // 刷新列表
              this.getStageList();
            } else {
              throw new Error(response.msg || "保存失败");
            }
          })
          .catch(error => {
            console.error("新增阶段失败:", error);
            this.$message.error(error.message || "新增失败");
            // 删除临时阶段
            const index = this.stageList.findIndex(s => s.id === stage.id);
            if (index !== -1) {
              this.stageList.splice(index, 1);
            }
          });
      }
    },

    /** 生成UUID */
    generateUUID() {
      function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
      }

      return (
        S4() +
        S4() +
        "-" +
        S4() +
        "-" +
        S4() +
        "-" +
        S4() +
        "-" +
        S4() +
        S4() +
        S4()
      );
    },

    /** 添加阶段 */
    handleAddStage() {
      // 生成临时ID
      const tempId = `temp-${Date.now()}-${this.stageIdCounter++}`;

      // 创建新阶段对象
      const newStage = {
        id: tempId,
        stageName: "",
        isNew: true,
      };

      // 添加到列表
      this.stageList.push(newStage);

      // 聚焦到新添加的输入框
      this.$nextTick(() => {
        const inputs = document.querySelectorAll(".stage-input input");
        const lastInput = inputs[inputs.length - 1];
        if (lastInput) {
          lastInput.focus();
        }
      });
    },
    /** 获取阶段列表 */
    getStageList() {
      const params = {
        pageNum: 1,
        pageSize: 999, // 确保获取所有数据
      };
      // 添加 loading 状态
      this.loading = true;
      return listStage(params)
        .then(response => {
          if (response.code === 200) {
            // 确保返回的数据是数组
            const stages = Array.isArray(response.rows) ? response.rows : [];
            // 格式化每个阶段对象
            this.stageList = stages.map(stage => ({
              id: stage.id,
              stageName: stage.stageName || "",
              isNew: false,
            }));
          } else {
            throw new Error(response.msg || "获取阶段列表失败");
          }
        })
        .catch(error => {
          console.error("获取阶段列表失败:", error);
          this.$message.error(error.message || "获取阶段列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /** 拖拽开始 */
    handleDragStart(event, stage) {
      if (stage.isNew) {
        event.preventDefault();
        return;
      }

      if (this.usedStages.has(stage.id)) {
        event.preventDefault();
        this.$message.warning("该阶段已添加到流程图中");
        return;
      }

      this.draggedStage = stage;
      event.dataTransfer.setData("text/plain", "");
    },

    beforeDestroy() {
      if (this.jsPlumbInstance) {
        try {
          this.jsPlumbInstance.reset();
          this.jsPlumbInstance = null;
        } catch (error) {
          console.error("Error destroying jsPlumb:", error);
        }
      }
    },

    /** 拖拽放置 */
    handleDrop(event) {
      event.preventDefault();
      if (!this.draggedStage) return;
      if (this.usedStages.has(this.draggedStage.id)) {
        this.$message.warning("该阶段已添加到流程图中");
        return;
      }
      const containerRect = this.$refs.flowContainer.getBoundingClientRect();
      let left, top;
      if (this.flowStages.length === 0) {
        left = 50;
        top = containerRect.height / 2 - 20;
      } else {
        const lastNode = this.flowStages[this.flowStages.length - 1];
        left = parseFloat(lastNode.style.left) + this.nodeSpacing; // 使用统一的间距
        top = parseFloat(lastNode.style.top);
      }
      const newStage = {
        id: `flow-${this.stageIdCounter++}`,
        templateId: this.form.id, // 添加模板ID
        stageName: this.draggedStage.stageName,
        originalId: this.draggedStage.id,
        style: {
          position: "absolute",
          left: `${left}px`,
          top: `${top}px`,
          width: "120px",
          height: "40px",
        },
      };
      this.usedStages.add(this.draggedStage.id);
      this.flowStages.push(newStage);
      this.$nextTick(() => {
        const sourceElement = document.getElementById(
          this.flowStages[this.flowStages.length - 2]?.id
        );
        const targetElement = document.getElementById(newStage.id);
        if (sourceElement && targetElement && this.jsPlumbInstance) {
          this.jsPlumbInstance.connect({
            source: sourceElement,
            target: targetElement,
            anchors: ["Right", "Left"],
            endpoint: ["Dot", { radius: 4 }],
            connector: ["Flowchart", { cornerRadius: 5 }],
            paintStyle: { stroke: "#409EFF", strokeWidth: 2 },
            overlays: [
              [
                "Arrow",
                {
                  location: 1,
                  width: 10,
                  length: 10,
                },
              ],
            ],
          });
          this.connections.push({
            source: sourceElement.id,
            target: targetElement.id,
          });
        }
      });
      this.draggedStage = null;
    },

    handleStageDelete(index) {
      const stage = this.stageList[index];
      if (stage.isNew) {
        this.stageList.splice(index, 1);
        return;
      }

      this.$modal
        .confirm("是否确认删除该阶段？")
        .then(async () => {
          try {
            // 1. 删除数据库中的阶段
            await delStage(stage.id);

            // 2. 删除左侧列表中的阶段
            this.stageList.splice(index, 1);

            // 3. 找出右侧流程图中所有使用该阶段的节点
            const relatedFlowStages = this.flowStages.filter(
              fs => fs.originalId === stage.id
            );

            // 4. 如果有相关节点需要删除
            if (relatedFlowStages.length > 0) {
              // 记录所有需要删除的节点索引
              const indexesToDelete = relatedFlowStages
                .map(fs => this.flowStages.findIndex(s => s.id === fs.id))
                .sort((a, b) => b - a); // 从后往前删除

              // 删除相关节点
              indexesToDelete.forEach(idx => {
                if (idx > -1) {
                  this.flowStages.splice(idx, 1);
                }
              });

              // 从已使用集合中移除
              this.usedStages.delete(stage.id);

              // 如果是当前选中的阶段，清除选中状态
              if (
                this.selectedStage &&
                relatedFlowStages.some(fs => fs.id === this.selectedStage.id)
              ) {
                this.selectedStage = null;
                this.achievementList = [];
              }

              // 等待 DOM 更新
              await this.$nextTick();

              // 重建流程图
              await this.rebuildFlowChart();
            }

            this.$modal.msgSuccess("删除成功");
          } catch (error) {
            console.error("删除阶段失败:", error);
            this.$modal.msgError(error.message || "删除失败");
          }
        })
        .catch(() => {});
    },

    /** 点击阶段节点 */
    handleStageClick(stage) {
      this.selectedStage = stage;
      // 获取或初始化该阶段的成果列表
      this.achievementList = this.stageAchievements[stage.id] || [];
    },

    /** 添加成果 */
    handleAddAchievement() {
      if (!this.selectedStage) return;

      const newAchievement = {
        stageId: this.selectedStage.id,
        achievementName: "",
        isRequired: 1,
      };
      this.achievementList.push(newAchievement);
      // 更新存储
      this.stageAchievements[this.selectedStage.id] = this.achievementList;
    },
    getProductList() {
      this.queryProductParams.productStatus = "已上架";
      listQualification(this.queryProductParams).then(response => {
        this.productList = response.rows;
        this.productTotal = response.total;
      });
    },
    /** 删除成果 */
    handleDeleteAchievement(index) {
      this.achievementList.splice(index, 1);
      // 更新存储
      this.stageAchievements[this.selectedStage.id] = this.achievementList;
    },
    /** 打开产品选择弹窗 */
    handleSelectProduct() {
      this.resetForm("queryProductForm");
      this.queryProductParams.pageNum = 1;
      this.queryProductParams.pageSize = 5;
      // 获取产品列表并处理选中状态
      listQualification({
        ...this.queryProductParams,
        productStatus: "已上架",
      }).then(response => {
        this.productList = response.rows;
        this.productTotal = response.total;
        // 打开弹窗并设置选中状态
        this.$nextTick(() => {
          this.productDialogVisible = true;
          // 使用 setTimeout 确保表格完全渲染
          setTimeout(() => {
            const table = this.$refs.productTable;
            if (table) {
              // 如果是编辑状态且有已选产品
              if (this.form.productId) {
                const productIds = this.form.productId.includes(",")
                  ? this.form.productId.split(",")
                  : [this.form.productId];
                this.productList.forEach(product => {
                  if (productIds.includes(product.id)) {
                    table.toggleRowSelection(product, true);
                    if (!this.selectedProducts.some(p => p.id === product.id)) {
                      this.selectedProducts.push(product);
                    }
                  }
                });
              }
            } else {
              console.warn("未找到产品表格引用");
            }
          }, 100);
        });
      });
    },

    /** 产品选择变更 */
    handleProductSelectionChange(selection) {
      this.selectedProducts = selection;
    },

    /** 删除流程图中的节点 */
    async deleteFlowStage(stage) {
      try {
        await this.$modal.confirm("是否确认删除该阶段？");

        // 1. 找到要删除节点的索引
        const index = this.flowStages.findIndex(s => s.id === stage.id);

        // 2. 从流程图节点列表中移除
        if (index > -1) {
          this.flowStages.splice(index, 1);
        }

        // 3. 从已使用集合中移除
        this.usedStages.delete(stage.originalId);

        // 4. 如果删除的是当前选中的阶段，清除选中状态
        if (this.selectedStage && this.selectedStage.id === stage.id) {
          this.selectedStage = null;
          this.achievementList = [];
        }

        // 5. 等待 DOM 更新
        await this.$nextTick();

        // 6. 重建流程图并等待完成
        await this.rebuildFlowChart();

        this.$modal.msgSuccess("删除成功");
      } catch (error) {
        if (error) {
          console.error("Error in deleteFlowStage:", error);
          this.$modal.msgError("删除失败");
        }
      }
    },

    rebuildFlowChart() {
      return new Promise(resolve => {
        // 1. 销毁现有的 jsPlumb 实例
        if (this.jsPlumbInstance) {
          this.jsPlumbInstance.reset();
          this.jsPlumbInstance.destroy();
          this.jsPlumbInstance = null;
        }

        // 2. 等待 DOM 更新
        this.$nextTick(() => {
          // 3. 重新排列节点位置
          const baseLeft = 50;
          const spacing = 200;

          this.flowStages.forEach((stage, index) => {
            stage.style = {
              position: "absolute",
              left: `${baseLeft + spacing * index}px`,
              top: "200px",
              width: "120px",
              height: "40px",
            };
          });

          // 4. 创建新的 jsPlumb 实例
          this.jsPlumbInstance = jsPlumb.getInstance({
            Container: this.$refs.flowContainer,
            Connector: ["Flowchart", { cornerRadius: 5 }],
            Endpoint: ["Dot", { radius: 4 }],
            PaintStyle: { stroke: "#409EFF", strokeWidth: 2 },
            EndpointStyle: { fill: "#409EFF" },
            HoverPaintStyle: { stroke: "#409EFF", strokeWidth: 3 },
            ConnectionsDetachable: false,
            Anchors: ["Right", "Left"],
          });

          // 5. 使用延迟确保 DOM 元素完全就绪
          setTimeout(() => {
            try {
              // 6. 创建连接
              this.flowStages.forEach((stage, index) => {
                if (index > 0) {
                  const sourceId = this.flowStages[index - 1].id;
                  const targetId = stage.id;

                  const sourceElement = document.getElementById(sourceId);
                  const targetElement = document.getElementById(targetId);

                  if (sourceElement && targetElement) {
                    this.jsPlumbInstance.connect({
                      source: sourceId,
                      target: targetId,
                      anchors: ["Right", "Left"],
                      endpoint: ["Dot", { radius: 4 }],
                      connector: ["Flowchart", { cornerRadius: 5 }],
                      paintStyle: { stroke: "#409EFF", strokeWidth: 2 },
                      overlays: [
                        [
                          "Arrow",
                          {
                            location: 1,
                            width: 10,
                            length: 10,
                          },
                        ],
                      ],
                    });
                  }
                }
              });

              // 7. 强制重绘
              this.jsPlumbInstance.repaintEverything();
              resolve();
            } catch (error) {
              console.error("Error creating connections:", error);
              resolve();
            }
          }, 300);
        });
      });
    },

    /** 重新排列流程图节点 */
    rearrangeFlowStages() {
      if (!this.jsPlumbInstance) {
        return;
      }
      const baseLeft = 50;
      const spacing = 200;
      try {
        // 重置所有连接
        this.jsPlumbInstance.deleteEveryConnection();
        // 重新排列节点位置
        this.flowStages.forEach((stage, index) => {
          stage.style = {
            position: "absolute",
            left: `${this.nodeBaseLeft + this.nodeSpacing * index}px`,
            top: "200px",
            width: "120px",
            height: "40px",
          };
        });
        // 使用 setTimeout 确保节点位置更新后再创建连接
        setTimeout(() => {
          // 重新创建连接
          this.flowStages.forEach((stage, index) => {
            if (index > 0) {
              const sourceId = this.flowStages[index - 1].id;
              const targetId = stage.id;
              this.jsPlumbInstance.connect({
                source: sourceId,
                target: targetId,
                anchors: ["Right", "Left"],
                endpoint: ["Dot", { radius: 4 }],
                connector: ["Flowchart", { cornerRadius: 5 }],
                paintStyle: { stroke: "#409EFF", strokeWidth: 2 },
                overlays: [
                  [
                    "Arrow",
                    {
                      location: 1,
                      width: 10,
                      length: 10,
                    },
                  ],
                ],
              });
            }
          });
        }, 50);
      } catch (error) {
        console.error("Error in rearrangeFlowStages:", error);
      }
    },

    // 确认产品选择
    confirmProductSelect() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning("请选择产品");
        return;
      }
      // 更新表单数据，多个产品名称用逗号分隔
      this.form.productName = this.selectedProducts
        .map(item => item.productName)
        .join(",");
      // 多个产品ID用逗号分隔
      this.form.productId = this.selectedProducts
        .map(item => item.id)
        .join(",");
      // 关闭弹窗
      this.productDialogVisible = false;
      // 触发表单验证
      this.$refs.formRef.validateField("productName");
    },

    /** 提交表单 */
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (!valid) {
          return;
        }
        // 构建保存的数据结构
        const templateData = {
          id: this.form.id,
          templateName: this.form.templateName,
          productIds: this.form.productId,
          productNames: this.form.productName,
          stages: this.flowStages.map((stage, index) => {
            const nextStage = this.flowStages[index + 1];
            const nextStageIds = nextStage ? nextStage.id : "";
            const left = parseFloat(stage.style.left);
            const top = parseFloat(stage.style.top);
            return {
              id: stage.id.startsWith("flow-") ? undefined : stage.id,
              templateId: this.form.id,
              stageName: stage.stageName,
              stageId: stage.originalId,
              stageOrder: index + 1,
              nextStageIds: nextStageIds,
              positionX: isNaN(left) ? 0 : left,
              positionY: isNaN(top) ? 0 : top,
              achievements: (this.stageAchievements[stage.id] || []).map(
                achievement => ({
                  id: achievement.id,
                  stageId: stage.id,
                  templateId: this.form.id,
                  achievementName: achievement.achievementName,
                  isRequired: achievement.isRequired || 0,
                  achievementOrder: achievement.achievementOrder,
                })
              ),
            };
          }),
        };

        // 数据验证
        let isValid = true;
        let errorMessage = "";
        // 验证流程阶段
        if (templateData.stages.length === 0) {
          this.$message.error("请至少添加一个流程阶段");
          return;
        }
        // 验证每个阶段的成果
        for (let i = 0; i < templateData.stages.length; i++) {
          const stage = templateData.stages[i];
          // 验证阶段名称
          if (!stage.stageName) {
            isValid = false;
            errorMessage = `第${i + 1}个阶段名称不能为空`;
            break;
          }
          // // 验证是否有成果
          // if (!stage.achievements || stage.achievements.length === 0) {
          //   isValid = false;
          //   errorMessage = `请为阶段"${stage.stageName}"添加至少一个成果`;
          //   break;
          // }

          // 验证成果信息
          // for (let j = 0; j < stage.achievements.length; j++) {
          //   const achievement = stage.achievements[j];
          //   if (!achievement.achievementName) {
          //     isValid = false;
          //     errorMessage = `阶段"${stage.stageName}"的第${
          //       j + 1
          //     }个成果名称不能为空`;
          //     break;
          //   }
          //   if (
          //     achievement.isRequired === undefined ||
          //     achievement.isRequired === null
          //   ) {
          //     isValid = false;
          //     errorMessage = `阶段"${stage.stageName}"的第${
          //       j + 1
          //     }个成果的必填字段不能为空`;
          //     break;
          //   }
          // }

          if (!isValid) break;
        }

        if (!isValid) {
          this.$message.error(errorMessage);
          return;
        }

        // 提交保存
        const submitMethod = this.opt === "edit" ? updateTemplate : addTemplate;
        submitMethod(templateData)
          .then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
              this.showEdit = false;
              this.getList();
            } else {
              throw new Error(response.msg || "保存失败");
            }
          })
          .catch(error => {
            console.error("保存模板失败:", error);
            this.$modal.msgError(error.message || "保存失败");
          });
      });
    },

    /** 取消按钮 */
    handleCancel() {
      this.showEdit = false;
      this.selectedStage = null;
      this.achievementList = [];
      this.stageAchievements = {};
      if (this.jsPlumbInstance) {
        this.jsPlumbInstance.reset();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/* 页面整体容器 */
.app-container {
  padding: 20px;
  height: calc(100vh - 84px); /* 设置高度为视口高度减去顶部导航栏高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

/* 设计页面整体布局 */
.design-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  overflow-y: auto; /* 添加垂直滚动条 */
}

/* 头部表单区域 */
.design-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  background: #fff;
}

/* 产品选择区域 */
.product-select {
  display: flex;
  align-items: center;
  gap: 10px;
}

.product-select .el-input {
  width: 200px;
}

/* 内容区域布局 */
.design-content {
  display: flex;
  padding: 20px;
  flex: 1;
  gap: 20px;
  min-height: 500px;
  overflow: hidden; /* 防止外层出现滚动条 */
  position: relative; /* 添加相对定位 */
}

/* 左侧阶段列表 */
.stage-list {
  width: 260px;
  min-width: 260px; // 添加最小宽度，防止被压缩
  border-right: 1px solid #eee;
  background: #f8f8f8;
  border-radius: 4px;
  position: relative;
  display: flex;
  flex-direction: column;
  height: 458px;
}

.stages-container {
  flex: 1;
  overflow-y: auto; /* 添加垂直滚动条 */
  padding: 20px;
  padding-bottom: 60px; /* 为底部按钮留出空间 */
  max-height: calc(100% - 40px); /* 减去新增阶段按钮的高度 */
}

/* 阶段项样式 */
.stage-item {
  background: #fff;
  border-radius: 4px;
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
}

.stage-item:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.stage-item:active {
  cursor: grabbing;
}

/* 阶段输入框 */
.stage-input {
  width: 100%;
}

.stage-item .el-input__inner {
  border: none;
  border-radius: 4px;
  padding: 8px 30px 8px 12px;
  height: 40px;
}

::v-deep {
  .design-content .el-input--medium .el-input__inner {
    text-align: center;
  }
}

/* 删除图标 */
.delete-icon {
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translateY(-50%);
  font-size: 14px;
  color: #f56c6c;
  cursor: pointer;
  opacity: 0;
  transition: all 0.3s;
  z-index: 1;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.stage-item:hover .delete-icon {
  opacity: 1;
}

.delete-icon:hover {
  background-color: rgba(245, 108, 108, 0.1);
  color: #ff4d4f;
}

/* 新增阶段按钮 */
.add-stage-btn {
  position: sticky; /* 改为sticky定位 */
  bottom: 0;
  left: 0;
  width: 100%;
  height: 40px;
  margin: 0;
  border: none;
  border-top: 1px solid #eee;
  border-radius: 0;
  background-color: #1890ff;
  transition: all 0.3s;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 确保按钮文字居中 */
.add-stage-btn span {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 右侧流程图区域 */
.flow-chart {
  flex: 1;
  min-height: 450px;
  background: #fff;
  border: 1px dashed #ddd;
  border-radius: 4px;
  position: relative;
  padding: 20px;
  background-image: linear-gradient(#eee 1px, transparent 1px),
    linear-gradient(90deg, #eee 1px, transparent 1px);
  background-size: 20px 20px;
  // 添加以下样式
  min-width: 800px; // 设置最小宽度
  overflow-x: auto; // 添加横向滚动
  overflow-y: hidden; // 防止出现垂直滚动条
}

/* 流程节点 */
.flow-node {
  position: absolute;
  width: 120px;
  height: 40px;
  background: #fff;
  border: 1px solid #409eff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  cursor: pointer;
  user-select: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 2;
  transition: all 0.3s;
}

.flow-node:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.flow-node.active {
  border-color: #409eff;
  background: #b8d0eb;
}

/* 节点文本 */
.node-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
  color: #333;
  font-size: 14px;
}

/* 节点删除图标 */
.flow-node .delete-icon {
  position: absolute;
  right: 5px;
  font-size: 14px;
  color: #f56c6c;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
}

.flow-node:hover .delete-icon {
  opacity: 1;
}

.flow-node .delete-icon:hover {
  color: #ff4d4f;
}

/* jsPlumb 连接线样式 */
._jsPlumb_connector {
  z-index: 1;
}

._jsPlumb_endpoint {
  z-index: 2;
}

._jsPlumb_overlay {
  z-index: 3;
}

/* 底部按钮区域 */
.design-footer {
  padding: 20px;
  text-align: center;
  border-top: 1px solid #eee;
  background: #fff;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 当页面内容高度超过容器高度时，显示滚动条 */
.app-container:hover::-webkit-scrollbar-thumb {
  background: #a8a8a8;
}

.app-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  transition: all 0.3s ease;
}

/* 拖拽相关样式 */
.dragging {
  opacity: 0.5;
}

.drag-over {
  border: 2px dashed #409eff;
}

/* 禁用状态 */
.disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

/* 加载状态 */
.loading {
  position: relative;
}

.loading::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.7);
  z-index: 999;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .design-content {
    flex-direction: column;
  }

  .stage-list {
    width: 100%;
    max-height: none;
    margin-bottom: 20px;
  }

  .flow-chart {
    min-height: 400px;
  }
}

/* 表单验证样式 */
.el-form-item.is-error .el-input__inner {
  border-color: #f56c6c;
}

/* 弹窗样式 */
.el-dialog__body {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式 */
.el-table {
  margin-top: 15px;
}

/* 成果列表样式 */
.achievement-list {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.achievement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.achievement-table {
  width: 100%;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

/* 按钮组样式 */
.btn-group {
  display: flex;
  gap: 10px;
}

/* 提示文本样式 */
.tip-text {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

/* 必填项标记 */
.required-label::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

/* 添加成果标题样式 */
.achievement-title {
  display: flex;
  margin-left: 15px;
  font-weight: bold;
  align-items: center;

  h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
  }
}
.no-data {
  font-size: 16px;
  color: #909399;
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80%;
}

/* 成果管理列表 */
.achievement-container {
  padding: 20px;
  border-top: 1px solid #eee;
  background: #fff;
  margin-bottom: 20px; /* 确保底部有空间 */
  overflow-x: auto; /* 添加水平滚动 */
}
</style>
